import React from 'react';
import './forms.scss'
import { useFormItemInit } from './hooks';
import { FormControl } from '../../utils/form/FormControl';
import { Utils } from '../../utils/utils';
import { WebUtils } from '../../utils/web';



interface IProps {
    formControl: FormControl,
    className?: string,
    style?: React.CSSProperties,
}
/**
 * 表单公共 Label
 * @param props 
 * @returns 
 */

const Label = React.forwardRef<any, IProps>((props, ref) => {
    const { formControl, className = '', style={} } = props;

    const { label } = useFormItemInit(formControl);

    const print = () => {
        console.log(formControl.label, formControl.controlData.key, formControl.value, formControl.selector);
        console.log(formControl);
        let replaced = false;   // 标记是否替换过
        let column_display_name = formControl.label;
        if (Utils.isNotEmpty(column_display_name)) {    // 字段中文名不为空的话
            if((window as any)['app_global'].replaceChatMsg){   // 先尝试替换聊天消息中的 '[字段]'
                replaced = (window as any)['app_global'].replaceChatMsg(column_display_name);
            }
            // 如果替换失败，则尝试复制字段中文名
            if(!replaced && navigator.clipboard && navigator.clipboard.writeText){
                navigator.clipboard.writeText(column_display_name);
            }
        }
        
    };

    const labelRef = React.useRef(null);

    const [title, setTitle] = React.useState(formControl.label);

    React.useEffect(() => {
        if (labelRef.current) {
            let t = '';
            const isLabelOverflow = WebUtils.checkTextOverflow(labelRef.current, '14px');
            const hasTips = (formControl.controlData.tips ?? '') === '' ? false : true;
            if (isLabelOverflow) {
                t += formControl.label;
            }
            if (hasTips) {
                t += formControl.controlData.tips;
            }
            setTitle(t);
        }
    }, []);

    return (
        <>
            {
                formControl.controlData.showLabel &&
                <div title={title} className={`label ${className}`} style={style} ref={ref as React.RefObject<HTMLDivElement>} onClick={print}>
                    {
                        // valid ? <span className='valid-success'></span> : <span className="valid-fail">*</span>
                        formControl.required ? <span className="valid-fail">*</span> : <span className='valid-success'></span>
                    }
                    <span ref={labelRef} className='label-name'>
                        {label}
                    </span>
                </div>
            }
        </>
    )
});


export default Label;